<template>
  <div>
    <a-form :form="form" style="margin: 20px auto 0;text-align: left;" @keyup.enter.native="nextStep">
      <a-form-item>
        <a-input
          v-decorator="['mobile',validatorRules.mobile]"
          placeholder="手机号"
          size="large"
          type="text">
          <a-icon slot="prefix" :style="{ color: 'rgba(0,0,0,.25)' }" type="mobile"/>
        </a-input>
      </a-form-item>

      <a-row :gutter="16">
        <a-col :span="16" class="gutter-row">
          <a-form-item>
            <a-input
              v-decorator="['captcha',validatorRules.captcha]"
              placeholder="请输入"
              size="large"
              type="text">
              <a-icon slot="prefix" :style="{ color: 'rgba(0,0,0,.25)' }" type="mail"/>
            </a-input>
          </a-form-item>
        </a-col>
        <a-col :span="8" class="gutter-row">
          <a-button
            :disabled="state.smsSendBtn"
            class="getCaptcha"
            tabindex="-1"
            type="primary"
            v-text="!state.smsSendBtn && '获取验证码' || (state.time+' s')"
            @click.stop.prevent="getCaptcha"></a-button>
        </a-col>
      </a-row>

      <a-form-item>
        <a-input-password
          v-decorator="['newPassword',validatorRules.newPassword]"
          placeholder="新密码"
          size="large"
          type="password">
          <a-icon slot="prefix" :style="{ color: 'rgba(0,0,0,.25)' }" type="lock"/>
        </a-input-password>
      </a-form-item>

      <a-form-item>
        <a-input-password
          v-decorator="['confirmPassword',validatorRules.confirmPassword]"
          placeholder="确认密码"
          size="large"
          type="password">
          <a-icon slot="prefix" :style="{ color: 'rgba(0,0,0,.25)' }" type="lock"/>
        </a-input-password>
      </a-form-item>
    </a-form>

    <a-form-item style="margin-top:24px;margin-bottom: 12px">
      <a-button
        :disabled="loginBtn"
        :loading="loginBtn"
        class="login-button"
        htmlType="submit"
        size="large"
        style="width: 100%"
        type="primary"
        @click.stop.prevent="handleSubmit">
        确定
      </a-button>
    </a-form-item>
  </div>
</template>

<script>
import { getAction } from '@/api/manage'
import { aesEncrypt } from '@/utils/encryption/aesEncrypt'
import { postAction } from '../../api/manage'

export default {
  name: 'Step2',
  props: ['userList'],
  data() {
    return {
      form: this.$form.createForm(this),
      loginBtn: false,
      // accountName: this.userList.username,
      dropList: '0',
      show: true,
      state: {
        time: 60,
        smsSendBtn: false
      },
      formLogin: {
        captcha: '',
        mobile: '',
        newPassword: ''
      },
      validatorRules: {
        newPassword: { rules: [{ required: true, message: '请输入新的密码!', validator: 'click' }] },
        confirmPassword: { rules: [{ validator: this.validateConfirmPassword }] },
        mobile: { rules: [{ validator: this.validateMobile }] },
        captcha: { rules: [{ required: true, message: '请输入验证码!' }] }
      }
    }
  },
  computed: {},
  methods: {
    getCaptcha(e) {
      e.preventDefault()
      let that = this
      this.form.validateFields(['mobile'], { force: true }, (err, values) => {
          if (!values.mobile) {
            that.cmsFailed('请输入手机号')
          } else if (!err) {
            this.state.smsSendBtn = true
            let interval = window.setInterval(() => {
              if (that.state.time-- <= 0) {
                that.state.time = 60
                that.state.smsSendBtn = false
                window.clearInterval(interval)
              }
            }, 1000)

            const hide = this.$message.loading('验证码发送中..', 0)
            let smsParams = {}
            smsParams.mobileNum = aesEncrypt(values.mobile)
            getAction('/sys/sendSms', smsParams)
              .then(res => {
                if (!res.success) {
                  setTimeout(hide, 0)
                  this.cmsFailed(res.message)
                }
                console.log(res)
                setTimeout(hide, 500)
              })
              .catch(err => {
                setTimeout(hide, 1)
                clearInterval(interval)
                that.state.time = 60
                that.state.smsSendBtn = false
                this.requestFailed(err)
              })
          }
        }
      )
    },
    handleSubmit() {
      let that = this
      let params = {}
      that.loginBtn = true
      // 使用账户密码登录
      that.form.validateFields(['mobile', 'newPassword', 'captcha', 'confirmPassword'], { force: true }, (err, values) => {
        if (!err) {
          params.mobileNum = aesEncrypt(values.mobile)
          params.mobileCaptcha = values.captcha
          params.newPassword = aesEncrypt(values.newPassword)
          params.confirmPassword = aesEncrypt(values.confirmPassword)
          if (values.newPassword !== values.confirmPassword) {
            console.log(values.newPassword, values.confirmPassword)
            this.$notification['error']({
              message: '登录失败',
              description: '两次输入的密码不一致，请重新输入',
              duration: 4
            })
            this.loginBtn = false
            return
          } else {
            postAction('/sys/changePasswordByMobileNum', params)
              .then(res => {
                if (res.success) {
                  console.log(res)
                  this.$notification.success({
                    message: '密码修改成功'
                  })
                  that.loginBtn = false
                  this.$router.push({ path: '/user/login' })
                } else {
                  that.loginBtn = false
                  that.requestFailed(res)
                }
              })
          }
        } else {
          that.loginBtn = false
        }
      })
    },
    requestFailed(err) {
      console.log(err)
      this.$notification['error']({
        message: '登录失败',
        description:  err.message || '请求出现错误，请稍后再试',
        duration: 4
      })
      this.loginBtn = false
    },
    validateMobile(rule, value, callback) {
      if (!value || new RegExp(/^1([38][0-9]|4[579]|5[0-3,5-9]|6[6]|7[0135678]|9[89])\d{8}$/).test(value)) {
        callback()
      } else {
        callback('您的手机号码格式不正确!')
      }

    },
    validateConfirmPassword(rule, value, callback) {
      if (!value || value == this.form.getFieldValue('newPassword')) {
        callback()
      } else if (value !== this.form.getFieldValue('newPassword')) {
        callback('两次输入的密码不一致!')
      }

    },
    cmsFailed(err) {
      this.$notification['error']({
        message: '验证错误',
        description: err,
        duration: 4
      })
    },
    handleChangeSelect(value) {
      var that = this
      console.log(value)
      if (value == 0) {
        that.dropList = '0'
        that.show = true
      } else {
        that.dropList = '1'
        that.show = false
      }
    },
    validatePhone(rule, value, callback) {
      if (value) {
        var myreg = /^[1][3,4,5,7,8][0-9]{9}$/
        if (!myreg.test(value)) {
          callback('请输入正确的手机号')
        } else {
          callback()
        }
      } else {
        callback()
      }
    }
  }

}
</script>

<style lang="less" scoped>
.stepFormText {
  margin-bottom: 24px;
}

.ant-form-item-label,
.ant-form-item-control {
  line-height: 22px;
}

.getCaptcha {
  display: block;
  width: 100%;
  height: 40px;
}
</style>